package com.juyu.miliao.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.common.domain.WXInfo;

public class WXgetUserInfoUtil {
	private static final String WXurl = "https://api.weixin.qq.com/sns/userinfo";
	private static final String lang = "zh_CN"; // 非必选，默认为json,为了展现方便，调试器选用json格式。
	private final static Logger logger = LoggerFactory.getLogger(WXgetUserInfoUtil.class);

	public static WXInfo doGet(String access_token, String openid) {
		String response = null;
		HttpURLConnection httpURLConnection = null;
		BufferedReader br = null;
		String wxLoginUrl = "";
		try {
			wxLoginUrl = WXurl + "?access_token=" + access_token + "&" + "openid=" + openid + "&" + "lang=" + lang;
			URL url = new URL(wxLoginUrl);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
			String readLine = null;
			StringBuffer sb = new StringBuffer();
			while ((readLine = br.readLine()) != null) {
				sb.append(readLine);
			}
			response = sb.toString();
		} catch (Exception e) {
			logger.error("第三方登录微信异常:", e);
		} finally {
			httpURLConnection.disconnect();
			try {
				if (br != null) {
					br.close();
				}
			} catch (IOException ex) {
				logger.error("第三方登录微信异常:", ex);
			}
		}
		ObjectMapper mapper = new ObjectMapper();
		WXInfo wxInfo = null;
		try {
			wxInfo = mapper.readValue(response.toString(), WXInfo.class);
		} catch (Exception e) {
			logger.error("第三方登录微信异常:", e);
		}
		return wxInfo;
	}
}
